

import 'package:logger/logger.dart';
import 'package:moonplay/common/event_bus_utils.dart';
import 'package:moonplay/model/like_list_model.dart';
import 'package:moonplay/model/video_set_model.dart';
import 'package:moonplay/pages/common_page/common_text_page.dart';
import 'package:flutter/material.dart';
import 'package:moonplay/common/app_common.dart';
import 'package:moonplay/model/video_detail_model.dart';
import 'package:moonplay/pages/tencentplayer/util/common_util.dart';
import 'package:moonplay/pages/tencentplayer/window_video_page.dart';
import 'package:moonplay/utils/common_utils.dart';
import 'package:moonplay/widgets/video_page.dart';
import 'package:get/get.dart';

class VideoDetailPage extends StatefulWidget {
  final dynamic arguments;

  const VideoDetailPage({Key key, this.arguments}) : super(key: key);
  @override
  _VideoDetailPageState createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage> with SingleTickerProviderStateMixin {
  Orientation get orientation => MediaQuery.of(context).orientation;
  double _height;
  TabController _tabController;
  Future _futureBuilderFuture;
  VideoDetailModel videoDetailModel;
  LikeListModel likeListModel;
  VideoSetModel videoSetModel;
  
  int setNum = 1;  //当前选中剧集
  String videoPlayUrl;
  int videoVolume = 0;    //播放进度, 从历史记录过来的时候有用
  int sourceIndex = 0;

  List vType = ["mgtv", "lbm3u8", "pptv"];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2,vsync: this,);
    _height = ScreenUtil.getInstance().screenWidth;
    init();

    LogUtil.e("打印传递过来的VODID: ${Get.arguments['vodId']}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: commonFutureBuilder(
        context,
        future: _futureBuilderFuture,
        callWidget: videoDetailModel != null ? bodyWidget() : Container(),
        callTap: init
      ),
    );
  }

  Widget bodyWidget(){
    return Column(
      children: <Widget>[
        Container(
          width: double.infinity,
          height: orientation == Orientation.portrait ? ScreenUtil().getWidthPx(480) : _height, // 这里随意
          child: videoPlayUrl != null
          ? WindowVideoPage(playType: PlayType.network, vodName: "${videoDetailModel.vodName}${videoSetModel.totalList[sourceIndex].videoList[setNum-1].videoSetName}", dataSource: videoPlayUrl)
          // MyVideoPage(
          //   url: videoPlayUrl, 
          //   isLive: false, 
          //   nextEpisode: widgetChildNextEpisode,
          //   title: '${videoDetailModel.vodName}${videoSetModel.totalList[sourceIndex].videoList[setNum-1].videoSetName}',
          //   isNext: setNum < videoSetModel.totalList.length ? true : false,
          //   setNum: setNum,
          //   videoVolume: videoVolume,
          //   data: videoDetailModel
          // )
          : Container()
        ),
        Expanded(
          child: Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                Container(
                  width: double.infinity,
                  height: ScreenUtil().getWidthPx(88),
                  alignment: Alignment.centerLeft,
                  child: TabBar(
                    isScrollable: true,
                    //是否可以滚动
                    controller: _tabController,
                    labelColor: Color(0xffff426e),
                    indicatorColor: Color(0xffff426e),
                    unselectedLabelColor: Color(0xff666666),
                    labelStyle: TextStyle(fontSize: 15.0),
                    indicatorSize: TabBarIndicatorSize.label,
                    tabs: <Widget>[
                      Tab(text: '详情'),
                      Tab(text: '相关'),
                    ],
                  ),
                ),
                CommonStyle.bottomLine(),
                Expanded(
                  child: TabBarView(
                    controller: _tabController,
                    children: <Widget>[
                      _widgetDetail(),
                      _widgetAbout()
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ],
    );
  }

  //视频详情
  Widget _widgetDetail(){
    return Container(
      padding: EdgeInsets.symmetric(horizontal: ScreenUtil().getWidthPx(30)),
      child: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Column(
              children: <Widget>[
                Container(
                  height: ScreenUtil().getWidthPx(80),
                  alignment: Alignment.centerLeft,
                  child: Cmtext('${videoDetailModel.vodName}', style: TextStyle(fontSize: 16, color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold)),
                ),
                Container(
                  constraints: BoxConstraints(
                    minHeight: ScreenUtil().getWidthPx(50),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Cmtext('年份/地区: ', style: TextStyle(fontSize: 14, color: Theme.of(context).primaryColor)),
                      Expanded(
                        flex: 1,
                        child: Container(
                        child: Cmtext('${videoDetailModel.vodYear} / ${videoDetailModel.vodArea}', style: TextStyle(fontSize: 14, color: Theme.of(context).cardColor)),
                      ),
                      )
                    ],
                  )
                ),
                Container(
                  constraints: BoxConstraints(
                    minHeight: ScreenUtil().getWidthPx(50),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Cmtext('主演: ', style: TextStyle(fontSize: 14, color: Theme.of(context).primaryColor)),
                      Expanded(
                        flex: 1,
                        child: Container(
                        child: Cmtext('${videoDetailModel.vodActor}', style: TextStyle(fontSize: 14, color: Theme.of(context).cardColor)),
                      ),
                      )
                    ],
                  )
                ),
                Container(
                  constraints: BoxConstraints(
                    minHeight: ScreenUtil().getWidthPx(50),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Cmtext('导演: ', style: TextStyle(fontSize: 14, color: Theme.of(context).primaryColor)),
                      Expanded(
                        flex: 1,
                        child: Container(
                          child: Cmtext('${videoDetailModel.vodDirector}', style: TextStyle(fontSize: 14, color: Theme.of(context).cardColor)),
                        ),
                      )
                    ],
                  )
                ),
                SizedBox(height: 10,),
                CommonStyle.bottomLine(),
                Container(
                  height: ScreenUtil().getWidthPx(80),
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(bottom: ScreenUtil().getWidthPx(20)),
                  child: Row(
                    children: <Widget>[
                      Cmtext('播放线路', style: TextStyle(fontSize: 16, color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold)),
                      SizedBox(width: 4,),
                      Cmtext('(如遇播放出错请切换线路)', style: TextStyle(fontSize: 14, color: Colors.red),)
                    ],
                  )
                ),
                Container(
                  height: ScreenUtil().getWidthPx(80),
                  child: Row(
                    children: sourceList(),
                  ),
                ),
                SizedBox(height: 10,),
                Container(
                  height: ScreenUtil().getWidthPx(80),
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(bottom: ScreenUtil().getWidthPx(20)),
                  child: Row(
                    children: <Widget>[
                      Cmtext('选集', style: TextStyle(fontSize: 16, color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold)),
                      SizedBox(width: 4,),
                      Cmtext('(${videoDetailModel.vodRemarks})', style: TextStyle(fontSize: 14, color: Theme.of(context).cardColor),)
                    ],
                  )
                ),
              ],
            )
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 8.0,
              mainAxisSpacing: 8.0,
              childAspectRatio: 1.5,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return InkResponse(
                  highlightColor: Colors.transparent,
                  radius: 0,
                  onTap: (){
                    eventBus.fire(PauseVideo()); 
                    String _type = videoSetModel.totalList[sourceIndex].playType;
                    if (_type != "kby" && _type != "lbm3u8" && _type != "kbym3u8") {
                      // Get.toNamed("/CommonWebviewPage", arguments: {"videoSetUrl": videoSetModel.totalList[sourceIndex].videoList[index].videoSetUrl});
                      changeVideoUrl(videoSetModel.totalList[sourceIndex].videoList[index].videoSetUrl, index+1);
                    } else {
                      print("监听这个值的变化: ${setNum}");
                      widgetChildNextEpisode(index: index+1);
                    }
                  },
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: setNum == index+1 ? Color(0xffcccccc) : Color(0xfff5f8f8),
                      borderRadius: BorderRadius.all(Radius.circular(2))
                    ),
                    child: Cmtext('${videoSetModel.totalList[sourceIndex].videoList[index].videoSetName}', style: TextStyle(fontSize: 12),),
                  ),
                );
              },
              childCount: videoSetModel.totalList.length > 0 ? videoSetModel.totalList[sourceIndex].videoList.length : 0,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(height: 60,),
          )
        ]
      )
    );
  }

  //视频相关, 猜你喜欢
  Widget _widgetAbout(){
    return Container(
      padding: EdgeInsets.symmetric(horizontal: ScreenUtil().getWidthPx(30)),
      child: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: Column(
              children: <Widget>[
                Container(
                  height: ScreenUtil().getWidthPx(80),
                  alignment: Alignment.centerLeft,
                  child: Cmtext('简介', style: TextStyle(fontSize: 16, color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold)),
                ),
                Container(
                  constraints: BoxConstraints(
                    minHeight: ScreenUtil().getWidthPx(50)
                  ),
                  alignment: Alignment.centerLeft,
                  child: Cmtext('${videoDetailModel.vodContent}', style: TextStyle(fontSize: 14, color: Theme.of(context).primaryColor),),
                ),
                SizedBox(height: 20,)
              ],
            ),
          ),
          likeListModel != null
          ? SliverToBoxAdapter(
            child: Column(
              children: <Widget>[
                CommonStyle.bottomLine(),
                Container(
                  height: ScreenUtil().getWidthPx(80),
                  alignment: Alignment.centerLeft,
                  child: Cmtext('猜你喜欢', style: TextStyle(fontSize: 16, color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold)),
                ),
              ],
            ),
          )
          : SliverToBoxAdapter(),
          likeListModel != null
          ? SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 3.0,
              mainAxisSpacing: 3.0,
              childAspectRatio: 0.56,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int idx) {
                return InkResponse(
                  highlightColor: Colors.transparent,
                  radius: 0,
                  onTap: () async {
                    eventBus.fire(PauseVideo()); 
                    Get.toNamed('/VideoDetailPage', arguments: {"vodId": likeListModel.records[idx].vodId, "typeId1": likeListModel.records[idx].typeId1}, preventDuplicates: false);
                  },
                  child: Container(
                    child: Stack(
                      children: <Widget>[
                        Container(
                          height: double.infinity,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(4))
                          ),
                          child: Column(
                            children: <Widget>[
                              Container(
                                height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                                child: Stack(
                                  children: <Widget>[
                                    // Container(
                                    //   width: double.infinity,
                                    //   height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                                    //   decoration: BoxDecoration(
                                    //     borderRadius: BorderRadius.all(Radius.circular(4)),
                                    //     image: new DecorationImage(//背景图片
                                    //       image: NetworkImage('${likeListModel.records[idx].vodPic}'),
                                    //       fit: BoxFit.cover
                                    //     ),
                                    //   ),
                                    // ),
                                    Positioned(
                                      top: 0,
                                      left: 0,
                                      right: 0,
                                      bottom: 0,
                                      child: Container(
                                        width: double.infinity,
                                        height: ScreenUtil.getInstance().screenWidth / 3 / 0.75,
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.all(Radius.circular(4)),
                                        ),
                                        child: loadNetworkImage(likeListModel.records[idx].vodPic),
                                      ),
                                    ),
                                    Positioned(
                                      bottom: 0,
                                      left: 0,
                                      right: 0,
                                      child: Container(
                                        height: ScreenUtil().getWidthPx(60),
                                        alignment: Alignment.centerLeft,
                                        padding: EdgeInsets.only(left: ScreenUtil().getWidthPx(10)),
                                        decoration: BoxDecoration(
                                          color: Color.fromRGBO(0, 0, 0, 0.7),
                                          borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))
                                        ),
                                        child: Cmtext('${likeListModel.records[idx].vodRemarks}', style: TextStyle(color: Colors.white, fontSize: 11), overflow: TextOverflow.ellipsis,),
                                      )
                                    )
                                  ],
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  alignment: Alignment.center,
                                  child: Cmtext('${likeListModel.records[idx].vodName}', style: TextStyle(fontSize: 13),overflow: TextOverflow.ellipsis),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    )
                  ),
                );
              },
              childCount: likeListModel.records.length,
            ),
          )
          : SliverToBoxAdapter(),
          SliverToBoxAdapter(
            child: Container(height: 60,),
          )
        ]
      )
    );
  }

  List<Widget> sourceList(){
    List<Widget> _arrs = [];
    for (var i = 0; i < videoSetModel.totalList.length; i++) {
      Widget _addWidget = InkResponse(
        onTap: (){
          setState(() {
            setNum = 1;
            sourceIndex = i;
          });
        },
        child: Container(
          width: (MediaQuery.of(context).size.width - ScreenUtil().getWidthPx(30)) * 0.191,
          height: ScreenUtil().getWidthPx(70),
          padding: EdgeInsets.symmetric(horizontal: ScreenUtil().getWidthPx(10)),
          child: Container(
            decoration: BoxDecoration(
              color: sourceIndex == i ? Color(0xffff426e) : Color(0xfff5f8f8),
              borderRadius: BorderRadius.all(Radius.circular(4))
            ),
            alignment: Alignment.center,
            child: Cmtext('${nameRn(videoSetModel.totalList[i].playType)}', style: TextStyle(fontSize: 13, color: sourceIndex == i ? Color(0xffffffff) : Color(0xff333333)),),
          )
        ),
      );
      _arrs.add(_addWidget);
    }
    return _arrs;
  }

  /**
   * 切换播放源
   */
  widgetChildNextEpisode({index}) async {
    if(index != null) {
      setState(() {
        videoPlayUrl = null;
        setNum = index;
        videoVolume = 0;
      });
    } else {
      setState(() {
        setNum++;
        videoVolume = 0;
      });
    }
    await Future.delayed(Duration(milliseconds: 200));
    setState(() {
      videoPlayUrl = videoSetModel.totalList[sourceIndex].videoList[setNum-1].videoSetUrl;
    });
  }

  /**
   * 播放源为全网时
   */
  changeVideoUrl(url, index) async {
    setState(() {
      videoPlayUrl = null;
      setNum = index;
      videoVolume = 0;
    });
    String _url = await getVideoUrl(url);
    LogUtil.e(_url);
    await Future.delayed(Duration(milliseconds: 200));
    setState(() {
      videoPlayUrl = _url;
    });
  }

  setVideoPlayUrl() async {
    //如果是从历史列表过来的,则会带着当前播放进度, 这里做判断是否有, 如果有, 则继续历史播放
    if(Get.arguments['videoVolume'] != null) {
      setState(() {
        setNum = Get.arguments['setNum'];
        videoVolume = Get.arguments['videoVolume'];
        videoPlayUrl = videoSetModel.totalList[sourceIndex].videoList.length > 0 ? videoSetModel.totalList[sourceIndex].videoList[setNum-1].videoSetUrl : "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318231014076505.mp4";
      });
    } else {
      LogUtil.e(videoSetModel.totalList);
      if (videoSetModel.totalList.length > 0) {
        if (videoSetModel.totalList[sourceIndex].playType != "kby") {
          String _url = await getVideoUrl(videoSetModel.totalList[sourceIndex].videoList[0].videoSetUrl);
          setState(() {
            videoPlayUrl = _url;
          });
        } else {
          setState(() {
            videoPlayUrl = videoSetModel.totalList[sourceIndex].videoList.length > 0 ? videoSetModel.totalList[sourceIndex].videoList[0].videoSetUrl : "http://vfx.mtime.cn/Video/2019/03/18/mp4/190318231014076505.mp4";
          });
        }
      }
    }
  }

  nameRn(value) {
    String _val;
    if (value == "kby") {
      _val = "推荐";
    } else if (value == "qq"){
      _val = "腾讯";
    } else if (value == "youku"){
      _val = "优酷";
    } else if (value == "qiyi"){
      _val = "奇艺";
    } else if (value == "mgtv"){
      _val = "芒果";
    } else if (value == "sohu"){
      _val = "搜狐";
    } else if (value == "letv"){
      _val = "乐视";
    } else if (value == "pptv"){
      _val = "PPTV";
    } else if (value == "m1905"){
      _val = "1905";
    } else if (value == "wasu"){
      _val = "华数";
    } else if (value == "hanju"){
      _val = "韩剧";
    } else if (value == "fun"){
      _val = "风行";
    } else if (value == "lbm3u8"){
      _val = "线路①";
    } else if (value == "kbym3u8"){
      _val = "线路②";
    }
    return _val;
  }

  //网络初始化
  init(){
    setState(() {
      _futureBuilderFuture = initGetIndex(Get.arguments['vodId']);
    });
  }

  //请求集数列表
  initGetIndex(vodId) async {
    Map<String, dynamic> postData = {
      "vodId": vodId
    };
    var _res = await HttpUtil().request("getVideoDetail", data: postData, need_login: false);
    // LogUtil.e(_res);
    if(_res != null && _res['code'] == 200) {
      setState(() {
        videoDetailModel = VideoDetailModel.fromJson(_res['data']);
      });
      fiterPlayUrl();
      getLikeList(videoDetailModel.vodId, videoDetailModel.typeId);
    }
    return _res;
  }

  getLikeList(vodId, typeId) async {
    Map<String, dynamic> postData = {
      "vodId": vodId,
      "typeId": typeId,
    };
    var _res = await HttpUtil().request("getLikeList", data: postData, need_login: false);
    // LogUtil.e(_res);
    if(_res != null && _res['code'] == 200) {
      LikeListModel _list = LikeListModel.fromJson(_res['data']);
      for (var i = 0; i < _list.records.length; i++) {
        var vodPic = _list.records[i].vodPic;
        if (vodPic != "" && vodPic.substring(0, 6) == "upload") {
          _list.records[i].vodPic = "http://app.ydecai.cn/" + _list.records[i].vodPic;
        }
      }
      setState(() {
        likeListModel = _list;
      });
    }
    return _res;
  }

  fiterPlayUrl(){
    List totalList = [];
    //转换播放url
    // _isOneUrl为true时表示只有一条播放地址
    bool _isOneUrl = videoDetailModel.vodPlayNote == "" ? true : false;
    String url = videoDetailModel.vodPlayUrl;
    //将播放源转换成逗号分割
    String str = videoDetailModel.vodPlayFrom;
    String str1 = str.replaceAll(RegExp(r"\$", multiLine:true), "P");
    List vodPlayFromArrs = str1.replaceAll("PPP", ",").split(",");
    LogUtil.e("数组长度: ${vodPlayFromArrs.length}, ${vodPlayFromArrs}");

    int ix = url.indexOf("#");
    if(ix != -1) {
      /**如果里面有#号, 则还需要判断一下里面是否还有三个$$$, 如果有则转换为#号 */
      int _usa = url.indexOf("\$\$\$");
      if(_usa != -1) {
        url = url.replaceAll(RegExp(r"\$\$\$", multiLine:true), "PPP");
      }

      List _arrs = url.split("PPP");
      
      for (var i = 0; i < _arrs.length; i++) {
        String _jiheUrl = _arrs[i];
        int _jinhao = _jiheUrl.indexOf("###");
        if(_jinhao != -1) {
          _jiheUrl = _jiheUrl.replaceAll(RegExp(r"###", multiLine:true), "#");
        }
        List _subArr = _jiheUrl.split("#");
        List _testSubList = [];
        for (var q = 0; q < _subArr.length; q++) {
          var _getData = rnUrl(_subArr[q]);
          _testSubList.add(_getData);
        }
        var _pushData = {
          "playType": vodPlayFromArrs[i],
          "videoList": _testSubList
        };
        bool _status = false;
        for (var f = 0; f < vType.length; f++) {
          if(_pushData['playType'] == vType[f]) {
            _status = true;
          }
        }
        if(!_status) {
          totalList.add(_pushData);
        }
      }
      // LogUtil.e("数组打印: ${totalList}");
    } else {
      /**如果里面有#号, 则还需要判断一下里面是否还有三个$$$, 如果有则转换为#号 */
      int _usa = url.indexOf("\$\$\$");
      if(_usa != -1) {
        url = url.replaceAll(RegExp(r"\$\$\$", multiLine:true), "PPP");
      }

      List _arrs = url.split("PPP");
      for (var i = 0; i < _arrs.length; i++) {
        String _jiheUrl = _arrs[i];
        int _jinhao = _jiheUrl.indexOf("###");
        if(_jinhao != -1) {
          _jiheUrl = _jiheUrl.replaceAll(RegExp(r"###", multiLine:true), "#");
        }
        List _subArr = _jiheUrl.split("#");
        List _testSubList = [];
        for (var q = 0; q < _subArr.length; q++) {
          var _getData = rnUrl(_subArr[q]);
          _testSubList.add(_getData);
        }
        var _pushData = {
          "playType": vodPlayFromArrs[i],
          "videoList": _testSubList
        };
        bool _status = false;
        for (var f = 0; f < vType.length; f++) {
          if(_pushData['playType'] == vType[f]) {
            _status = true;
          }
        }
        if(!_status) {
          totalList.add(_pushData);
        }
      }
    }
    var _data = {
      "totalList": totalList
    };
    setState(() {
      videoSetModel = VideoSetModel.fromJson(_data);
    });
    setVideoPlayUrl();
  }

  rnUrl(url){
    Map<String, String> rnData = {
      "video_set_name": "",
      "video_set_url": ""
    };
    int _isIdx = url.indexOf(RegExp(r"\$"));
    //_isIdx!=-1时表示地址中找到了字符$,对播放地址进行分解
    if(_isIdx != -1) {
      /**
       * video_set_name=剧集名称
       * video_set_url=剧集播放地址
       */
      
      String video_set_name = url.substring(0, _isIdx);
      String video_set_url = url.substring(_isIdx+1);
      
      rnData = {
        'video_set_name': video_set_name,
        'video_set_url': video_set_url
      };
    }
    
    return rnData;
  }
}